//
//  AuthenticationController.m
//  HB
//
//  Created by 陶秋安 on 16/5/12.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "AuthenticationController.h"

@interface AuthenticationController ()

@end

@implementation AuthenticationController

- (void)viewDidAppear:(BOOL)animated
{
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    clubPhotoName =@"authentication.jpg";
    
    [self loadAuthenticationInfo];
    
    _imgClubPhoto.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *singleTap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(takePictureClick:)];
    
    [_imgClubPhoto addGestureRecognizer:singleTap1];
}

-(void) loadAuthenticationInfo
{
    NSString *djID= [Common getUserDefaults:@"djID"];
    
    operation= [[LoginOperation alloc] initWithDelegate:self];
    
    NSString *URL= [FxGlobal getServiceUrl:@"Mine" andFuncName:@"GetAuthentication"];
    
    NSString *finallUrl=[NSString stringWithFormat:@"%@?djID=%@",URL,djID];
    
    NSDictionary * dictInfo = @{@"url":finallUrl};
    
    [operation setOpInfo:dictInfo];
    
    [operation get:0];
}

-(void)opSuccessForGet:(id)data andFlag:(NSInteger)flag
{
    operation= nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data2 = [dataStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    
    if ([[data2 objectForKey:@"result"] isEqualToString:@"1"])
    {
        dispatch_async( dispatch_get_main_queue(), ^(void)
                       {
                           self.txtClubName.text= [data2 objectForKey:@"ClubName"];
                           self.txtClubCity.text= [data2 objectForKey:@"ClubCity"];
                           self.txtCardNo.text= [data2 objectForKey:@"CardNo"];
                       });
        
        clubPhoto=[data2 objectForKey:@"ClubPhoto"];
        
        [Common downLoadImageByURL:_imgClubPhoto andURL:clubPhoto andName:clubPhotoName];
    }
    
    
}

-(void) setBackBarButton
{
    
}

-(void)setNavigationLeft:(NSString *)imageName sel:(SEL)sel
{
    
    
}

- (void)setNavigationRight:(NSString *)imageName sel:(SEL)sel
{
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame = CGRectMake(0, 0, 44, 22);
    
    [btn setTitle:@"保存" forState:UIControlStateNormal];
    
    btn.titleLabel.font = [UIFont systemFontOfSize: 14.0];
    
    [btn addTarget:self action:@selector(saveAuthenticationRequest) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = item;
    
}

-(void) saveAuthenticationRequest
{
    
    
    if ([self.txtCardNo.text isEqualToString:@""]) {
        [UIView showAlertView:@"提示" andMessage:@"身份证号不能为空" andHost:self];
    }
    else if([self.txtClubName.text isEqualToString:@""]) {
        [UIView showAlertView:@"提示" andMessage:@"酒吧名称不能为空" andHost:self];
    }
    else if([self.txtClubCity.text isEqualToString:@""]) {
        [UIView showAlertView:@"提示" andMessage:@"酒吧所在城市不能为空" andHost:self];
    }
    else if( self.imgClubPhoto.image == nil ) {
        [UIView showAlertView:@"提示" andMessage:@"酒吧照片不能为空" andHost:self];
    }
    else
    {
        [UIView showAlertView:@"提示" andMessage:@"确定要保存吗？如已经认证，重复提交会导致认证失败。" andHost:self sel:^(UIAlertAction *action) {
            [self myTask];
        }];
    }
    
}

- (void)setNavigationTitleImage:(NSString *)imageName
{
    self.navigationItem.title = @"认证申请";
}

//从相册获取图片
-(void)takePictureClick:(UITapGestureRecognizer *)imgView
{
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"照相机",@"本地相簿",nil];
    [actionSheet showInView:self.view];
    
}

#pragma mark -
#pragma UIActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"buttonIndex = [%ld]",(long)buttonIndex);
    switch (buttonIndex) {
        case 0://照相机
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:(__bridge NSString *)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    }
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //    [picker dismissModalViewControllerAnimated:YES];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)image {
    
    BOOL success;
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSError *error;
    
    NSString *imageFilePath = [FxGlobal getCacheImage:clubPhotoName];
    
    success = [fileManager fileExistsAtPath:imageFilePath];
    
    if(success)
    {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    //创建小尺寸的图片
    //UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(93, 93)];
    
    [UIImageJPEGRepresentation(image, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取图片文件
    
    _imgClubPhoto.image = selfPhoto;
    
    [self uploadAction];
}

//上传头像
- (void)uploadAction
{
    NSString *url1= [FxGlobal getServiceUrl:@"Mine" andFuncName:@"ImgUploadAuthentication"];
    
    NSData *imgData=UIImageJPEGRepresentation(_imgClubPhoto.image, 0.9f);
    
    NSString *boundary = @"0xKhTmLbOuNdArY";//边界
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary, nil];
    
    NSURL *url=[NSURL URLWithString:url1];
    
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    [request setHTTPMethod:@"POST"];
    
    NSMutableData *body = [NSMutableData data];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Disposition: form-data; name=\"userfile\"; filename=\"iphonefile.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [body appendData:[NSData dataWithData:imgData]];
    
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [request setHTTPBody:body];
    
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue
                           completionHandler:^(NSURLResponse *respone,
                                               NSData *data,
                                               NSError *error)
     {
         if ([data length]>0 && error==nil)
         {
             
             
             NSError *err;
             
             NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&err];
             
             clubPhoto =  [dic objectForKey:@"fileName"];
             
             //保存数据
             
         }
     }];
}

- (void)myTask
{
    
    operation=[[LoginOperation alloc] initWithDelegate:self];
    
    NSString *url= [FxGlobal getServiceUrl:@"Mine" andFuncName:@"SaveAuthentication"];
    
    NSString *djID= [Common getUserDefaults:@"djID"];
    
    //NSString *imgUrl=[NSString stringWithFormat:@"http://%@/HeadImg/%@",serviceip,fileName];
    
    NSString *md5Str= [NSString stringWithFormat: @"CardNo=%@&ClubCity=%@&ClubName=%@&ClubPhoto=%@&ClubPhotoName=%@&djID=%@&key=tqa",self.txtCardNo.text,self.txtClubCity.text,
                       
                       self.txtClubName.text,clubPhoto,clubPhotoName,djID];
    
    NSString *sign = [Common createMD5:md5Str];
    
    NSString *body=[NSString stringWithFormat:@"{\"CardNo\":\"%@\",\"ClubCity\":\"%@\",\"ClubName\":\"%@\",\"ClubPhoto\":\"%@\",\"ClubPhotoName\":\"%@\",\"djID\":\"%@\",\"sign\":\"%@\",\"clicentid\":\"1\"}",self.txtCardNo.text,self.txtClubCity.text,
                    
                    self.txtClubName.text,clubPhoto,clubPhotoName,djID,sign];
    
    NSDictionary *dictInfo = @{@"url":url,@"body":body};
    
    [operation setOpInfo:dictInfo];
    
    [operation post];
    
}

-(void) opSuccessForPost:(id)data
{
    operation=nil;
    
    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSDictionary *data1 = [dataStr objectFromJSONString];
    
    NSString *v=[data1 objectForKey:@"result"];
    
    if([v isEqualToString:@"1"])
    {
        
        
    }
    else if([v isEqualToString:@"6000001"])
    {
        [UIView showAlertView:@"提示" andMessage:@"您还有尚未处理的请求，不能重复提交" andHost:self];
    }
    
}



@end
